﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DevExpress.Web.Mvc;
using Webcar.BLL;
using Webcar.Entitys;
using Webcar.Utils;
using System.Data.Entity;
using System.Web.UI.WebControls;
using System.Threading;
using EntityFramework.Extensions;
namespace Webcar.Controllers
{
    
    public partial class CarController : BaseControler
    {
        public ActionResult Edit(string carno,string deptcode)
        {
            BS_CAR_RECORD car=null;
            if (carno.IsNotNull())
            {
                car = WebcarDataProvider.DB.BS_CAR_RECORD.Find(carno);
            }
            if(car==null)
            {
                car = new BS_CAR_RECORD();
                car.DEPT_CODE = deptcode;
                car.IS_USE = "T";
            }
            
            var dept = WebcarDataProvider.DB.sys_dept.Find(car.DEPT_CODE);
            if (dept != null)
                ViewBag.DeptName = dept.deptname;
            
            return PartialView(car);
        }
        bool CheckCarModel(BS_CAR_RECORD model,ref string error)
        {
            if (model.SHELF_NO.IsNotNull()&&model.SHELF_NO.Length != 17)
            {
                error = "车架号必须17位。";
                return false;
            }
            if (model.ENGINE_NO.Trim().IsNull())
            {
                error = "请录入引擎号。";
                return false;
            }
            if (model.VALUE==null)
            {
                error = "请录入车辆价格。";
                return false;
            }
            if (model.CARRY_WEIGHT == null)
            {
                error = "请录入车辆载重。";
                return false;
            }
            if (model.FUEL_100MILE == null)
            {
                error = "请录入车辆油耗。";
                return false;
            }
            if (model.COLOR.IsNull())
            {
                error = "请录入车辆颜色。";
                return false;
            }
            //是否车牌重复
            var exist = WebcarDataProvider.DB.BS_CAR_RECORD.FirstOrDefault(a => a.RECORD_NO == model.RECORD_NO);
            if (exist!= null&&exist.CAR_NO!=model.CAR_NO)
            {
                string status = WebcarDataHelper.CarStatusCode.FirstOrDefault(a => a.Item1 == exist.CAR_USE.IsNull("T")).Item2;
                

                error = "车牌["+model.RECORD_NO+"]已经存在，车辆状态为["+status+"],请检查。";
                return false;
            }

            return true;
        }

        [HttpGet]
        public ActionResult SetTzFlag(string id, bool tz_flag)
        {
            string sql = "update bs_car_record set car_class2='{0}' where car_no='{1}'";
            sql = sql.FormatWith(tz_flag ? "TZ" : "", id);
            WebcarDataProvider.DB.ObjectContext.ExecuteStoreCommand(sql);
            return Content("OK");
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult EditSave(BS_CAR_RECORD model)
        {
            CurrentUser.EnsurePermission(PermissionManager.编辑车辆档案);
            try
            {
                string error = "";
                if (this.CheckCarModel(model, ref error) == false)
                {
                    return Content("错误:" + error);
                }
                using (var DB = new WebcarContext())
                {
                    BS_CAR_RECORD item = null;
                    if (model.CAR_NO.IsNotNull())
                    {
                        item = DB.BS_CAR_RECORD.Find(model.CAR_NO);
                    }
                    else
                    {
                        item = new BS_CAR_RECORD();
                        DB.BS_CAR_RECORD.Add(item);
                        item.IS_USE = "T";
                    }
                    model.CopyPropertyTo(item);
                    if (item.CAR_NO.IsNull())
                        item.CAR_NO = "C" + DB.GetSearialId();
                    DB.SaveChanges();
                }
                return SuccessAlertThenReload();
            }
            catch (Exception ex)
            {
                return this.ErrorContent(ex);
            }
        }
        [HttpGet]
        public ActionResult List()
        {
            //CurrentUser.EnsurePermission(PermissionManager.查看车辆列表);
            ViewBag.ShowOptions = new ShowCarOptions() { ShowNormal =true};
            HttpContext.Session["ShowCarOptions"] = ViewBag.ShowOptions;
            return View("List");
        }
        [HttpPost]
        public ActionResult List(ShowCarOptions options)
        {
            ViewBag.ShowOptions = options;
            HttpContext.Session["ShowCarOptions"] = options;
            return View();
        }

        public ActionResult ListPartialView(string id,string type)
        {
            return PartialView();
        }
        public ActionResult Delete(string id)
        {
            /*
             * BS_CAR_PHOTO
                BS_CAR_RECORD
                BS_CAR_DISCARD
                BS_CAR_MILE
                BS_CAR_MOVE
                BS_CAR_SEND
                BS_EMP
                BS_INSURE
                bs_car_runrecord
                RP_CAR_REPAIR_HEAD
                SEC_RECORD
             */
            CurrentUser.EnsureAdmin();
            CurrentUser.EnsurePermission(PermissionManager.编辑车辆档案);
            using (var DB = new WebcarContext())
            {
                DB.BS_CAR_RECORD.Delete(a => a.CAR_NO == id);
                DB.bs_car_runrecord.Delete(a => a.car_no == id);
                DB.BS_CAR_MOVE.Delete(a => a.CAR_NO == id);
                DB.BS_CAR_DISCARD.Delete(a => a.CAR_NO == id);
                DB.BS_CAR_PHOTO.Delete(a => a.CAR_NO == id);
                DB.BS_CAR_MILE.Delete(a => a.CAR_NO == id);
                DB.BS_CAR_SEND.Delete(a => a.car_no == id);
                DB.RP_CAR_REPAIR_HEAD.Delete(a => a.CAR_NO == id);
                DB.SEC_RECORD.Delete(a => a.CAR_NO == id);
                DB.BS_INSURE.Delete(a => a.CAR_NO == id);
                DB.SaveChanges();
            }
            return RedirectToAction("List", "Car");
        }

        public ActionResult DeleteFlag(string id)
        {
            CurrentUser.EnsurePermission(PermissionManager.编辑车辆档案);
            using (var DB = new WebcarContext())
            {
                var car = DB.BS_CAR_RECORD.Find(id);
                if (car != null)
                {
                    car.IS_USE = "D";
                    DB.SaveChanges();
                    return RedirectToAction("List", "Car", new { id = car.DEPT_CODE });
                }
            }
            return RedirectToAction("List", "Car");
        }

        public ActionResult Export()
        {
            GridViewSettings settings = new GridViewSettings();
            settings.Name = "gridView";
            settings.Columns.Add("RECORD_NO", "牌照号");
            settings.AddDeptColumn();//.AddChildDeptColumn();
            settings.AddCarSortColumn();
            settings.Columns.Add("car_class_name", "详细车型");
            settings.Columns.Add("BUY_DATE", "购置日期", MVCxGridViewColumnType.DateEdit).PropertiesEdit.DisplayFormatString = "yyyy-MM-dd";
            settings.Columns.Add("INSURE_DATE", "保险到期日期", MVCxGridViewColumnType.DateEdit).PropertiesEdit.DisplayFormatString = "yyyy-MM-dd";
            settings.Columns.Add("VALUE", "价格");
            settings.Columns.Add("GUEST_NUM", "载客(人)");
            settings.Columns.Add("IS_TZ_CN", "特种车辆");
            settings.AddCarStatusColumn();
            var data = UserDataProvider.GetCarList(this.RouteData).ToDataTable();
            return GridViewExtension.ExportToXls(settings, data,"车辆档案");
            
            //return RedirectToAction("List", "Car");
        }

    }
    public class ShowCarOptions
    {
        public bool ShowNormal
        {
            get;
            set;
        }
        public bool ShowDelete
        {
            get;
            set;
        }
        public bool ShowDiscard
        {
            get;
            set;
        }

    }
}